import com.sun.jersey.api.client.ClientHandlerException;
import com.sun.jersey.api.client.ClientRequest;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.filter.ClientFilter;
import com.sun.jersey.core.util.Base64;
import org.springframework.core.io.ClassPathResource;

import javax.crypto.Cipher;
import javax.ws.rs.core.HttpHeaders;
import java.security.Key;
import java.security.KeyStore;
import java.security.cert.Certificate;


public final class ISellAuthenticationClientFilter extends ClientFilter {

    private final String authentication;

    public ISellAuthenticationClientFilter(final String username, final String password) {
        try {
            ClassPathResource keyStoreResource = new ClassPathResource("publicKey.store");
            KeyStore publicKeyStore = KeyStore.getInstance("JKS");
            publicKeyStore.load(keyStoreResource.getInputStream(), "isellpass".toCharArray());

            Certificate certificate = publicKeyStore.getCertificate("isell");

            Key isell = certificate.getPublicKey();
            System.out.println(isell.getFormat());
            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            cipher.init(Cipher.ENCRYPT_MODE, isell);
            byte[] bytes = cipher.doFinal((username + ":" + password).getBytes());
            authentication = "ISell " + new String(Base64.encode(bytes), "UTF-8");

        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    @Override
    public ClientResponse handle(final ClientRequest cr) throws ClientHandlerException {

        if (!cr.getMetadata().containsKey(HttpHeaders.AUTHORIZATION)) {
            cr.getMetadata().add(HttpHeaders.AUTHORIZATION, authentication);
        }
        return getNext().handle(cr);
    }
}